package com.atguigu2.statement.crud;

import com.atguigu3.util.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Scanner;

/**
 * 演示使用PreparedStatement替换Statement解决sql注入问题
 *
 *除了解决Statement的拼串问题外，使用PreparedStatement还有一下的好处
 *1.PreparedStatement可以操作Blob问题，但是Statement不行
 *2.PreparedStatement可以实现高效的批量操作
 */
public class PreparedStatementTest {
    @Test
    public void testLogin() {
        // 使用Statement的弊端：需要拼写sql语句，并且存在SQL注入的问题
        //如何避免SQL注入，只需要将PreparedStatement（congStatement扩展而来）替换Statement
        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入用户名：");
        String user = scanner.nextLine();
        System.out.println("请输入密码：");
        String password = scanner.nextLine();

        //sql注入
        //SELECT user,password FROM user_table WHERE user = '1' or ' AND password = '=1 or '1' = '1'
        String sql = "SELECT user,password FROM user_table WHERE user = ? AND password = ?";
        User returnUser = getInstance(User.class, sql,user,password);

        if (returnUser != null) {
            System.out.println("登陆成功");
        } else {
            System.out.println("用户名不存在或密码错误");
        }

    }

    public <T> T getInstance(Class<T> clazz, String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }

            rs = ps.executeQuery();

            ResultSetMetaData rsmd = rs.getMetaData();

            int columnCount = rsmd.getColumnCount();

            if (rs.next()) {
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    Object columnValue = rs.getObject(i + 1);

                    String columnLabel = rsmd.getColumnLabel(i + 1);
                    Field field = clazz.getDeclaredField(columnLabel);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                return t;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps, rs);
        }
        return null;
    }
}


